package com.ybb.vue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ybb.vue.common.R;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.AntianaphylaxisUtils;
import com.ybb.vue.common.util.ExcelUtils;
import com.ybb.vue.common.util.OperationRecordsUtils;
import com.ybb.vue.domain.HealthStatusEnum;
import com.ybb.vue.domain.vo.EpmResidentDetailVo;
import com.ybb.vue.domain.vo.EpmResidentExportVo;
import com.ybb.vue.domain.dto.EpmResidentSaveDto;
import com.ybb.vue.domain.dto.EpmResidentUpdateDto;
import com.ybb.vue.domain.vo.EpmResidentImportTempVo;
import com.ybb.vue.entity.EpmResident;
import com.ybb.vue.mapper.EpmResidentMapper;
import com.ybb.vue.service.EpmResidentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ybb
 * @version 1.0
 * @Description 居民表controller
 * @Date 2023/3/6 13:00
 */
@RestController
@RequestMapping("/resident")
public class EpmResidentController {

    @Autowired
    private EpmResidentService residentService;

    @Autowired
    private EpmResidentMapper residentMapper;

    /**
     * 查询resident列表
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping("/residentList")
    @PreAuthorize("hasAuthority('epidemic:prevention:list')"+"||"+"hasAuthority('epidemic:prevention:query')")
    public Result<?> residentList (@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search) {
        Page<EpmResident> result = residentService.page(new Page<>(pageNum, pageSize), Wrappers.<EpmResident>lambdaQuery().like(EpmResident::getName, search));
        List<EpmResident> residentList = result.getRecords();
        residentList.forEach(resident -> {
            // 联系方式和身份证好进行脱敏处理
            resident.setPhoneNumber(AntianaphylaxisUtils.antianaphylaxisUtil(3,8,resident.getPhoneNumber()));
            resident.setIdCard(AntianaphylaxisUtils.antianaphylaxisUtil(3, 15, resident.getIdCard()));
            // 健康码转译
            resident.setHealthStatus(HealthStatusEnum.getHealthStatus(resident.getHealthStatus()));
        });
        return Result.success(result);
    }

    /**
     * 添加
     * @param residentSaveDto
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('epidemic:prevention:add')")
    public Result<?> save(@RequestBody @Valid EpmResidentSaveDto residentSaveDto){
        return residentService.saveResident(residentSaveDto);
    }

    /**
     * 修改
     * @param residentUpdateDto
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('epidemic:prevention:edit')")
    public Result<?> update(@RequestBody @Valid EpmResidentUpdateDto residentUpdateDto){
        return residentService.updateResident(residentUpdateDto);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('epidemic:prevention:delete')")
    public R delete(@RequestBody String[] ids){
        residentService.removeByIds(Arrays.asList(ids));

        // 操作记录
        String content = "操作了居民表，【删除】了"+Arrays.asList(ids).size()+"条记录，记录id为：" + ids;
        OperationRecordsUtils.createOperationRecords(content);
        return R.ok();
    }

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/import")
    @PreAuthorize("hasAuthority('epidemic:prevention:import')")
    public Result<?> importResident(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.error("-1","未选择文件！");
        }
        String fileName = file.getOriginalFilename();
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i+1);
        }
        if (!"xlsx".equals(extension)) {
            return Result.error("-1","文件格式错误！");
        }
        return residentService.importResident(file);
    }

    /**
     * 导出
     * @param response
     * @param search
     */
    @GetMapping("/export")
    @PreAuthorize("hasAuthority('epidemic:prevention:export')")
    public void exportResident(HttpServletResponse response,@RequestParam(defaultValue = "") String search) {
        List<EpmResident> residentList = residentMapper.selectList(new QueryWrapper<EpmResident>().lambda().like(EpmResident::getName, search));
        List<EpmResidentExportVo> exportList = new ArrayList<>();
        residentList.forEach(resident -> {
            EpmResidentExportVo residentExportVo = new EpmResidentExportVo();
            BeanUtils.copyProperties(resident, residentExportVo);
            residentExportVo.setHealthStatus(HealthStatusEnum.getHealthStatus(residentExportVo.getHealthStatus()));
            exportList.add(residentExportVo);
        });
        ExcelUtils.export(response, "居民信息表", exportList, EpmResidentExportVo.class);

    }

    /**
     * 模版下载
     * @param response
     */
    @GetMapping("/templateDown")
    @PreAuthorize("hasAuthority('epidemic:prevention:export')")
    public void templateDown(HttpServletResponse response) {
        ExcelUtils.exportTemplate(response, "居民信息表导入模版", EpmResidentImportTempVo.class);
    }

    /**
     * 居民信息详情
     * @param id
     * @return
     */
    @GetMapping("/residentDetail")
    @PreAuthorize("hasAuthority('epidemic:prevention:detail')")
    public Result<?> residentDetail(String id) {
        EpmResidentDetailVo residentDetailVo = new EpmResidentDetailVo();
        EpmResident resident = residentMapper.selectById(id);
        BeanUtils.copyProperties(resident, residentDetailVo);
        residentDetailVo.setHealthStatus(HealthStatusEnum.getHealthStatus(residentDetailVo.getHealthStatus()));
        return Result.success(residentDetailVo);
    }

    /**
     * 居民信息详情 无权限  首页使用
     * @param id
     * @return
     */
    @GetMapping("/residentDetailByIndex")
    public Result<?> residentDetailByIndex(String id) {
        EpmResidentDetailVo residentDetailVo = new EpmResidentDetailVo();
        EpmResident resident = residentMapper.selectById(id);
        BeanUtils.copyProperties(resident, residentDetailVo);
        residentDetailVo.setHealthStatus(HealthStatusEnum.getHealthStatus(residentDetailVo.getHealthStatus()));
        return Result.success(residentDetailVo);
    }
}
